﻿namespace JoinBox.WPF;

using System;
using System.Threading;
using System.Windows.Threading;
using System.Windows;

public class SyncEx2WPF : Basal.SyncContext
{
    public Window? Window;

    /// <summary>
    /// 处理WPF上下文
    /// </summary>
    /// <param name="window"></param>
    public SyncEx2WPF(Window window)
    {
        Window = window ?? throw new ArgumentException(null, nameof(window));
    }

    /// <summary>
    /// 加载事件,因为显示之后才确定分配了线程
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    public void Loaded()// object? sender = null/*, System.Windows.RoutedEventArgs? e = null*/
    {
        // 空闲时候执行的事件
        DispatcherTimer((sender1, e1) => {
            WaitOne();
        });
    }

    #region 用计时器仿WinForm空闲事件,放在WPF的Loaded事件上
    /// <summary>
    /// 空闲事件
    /// </summary>
    public event EventHandler? Idle;
    /// <summary>
    /// 用计时器仿WinForm空闲事件
    /// </summary>
    void DispatcherTimer(Action<object, EventArgs> idle)
    {
        if (idle is null)
            throw new ArgumentException(null, nameof(idle));

        Idle += idle.Invoke;

        var timer = new DispatcherTimer
        (
            TimeSpan.FromMilliseconds(1),
            DispatcherPriority.ApplicationIdle,// 或 DispatcherPriority.SystemIdle
            Idle,
            Dispatcher.CurrentDispatcher
        );
        timer.Start();
    }
    #endregion
}


